/*
 * @Author: Diana Tang
 * @Date: 2025-04-05 23:54:25
 * @LastEditors: Diana Tang
 * @Description: some description
 * @FilePath: /pub-scholar-assist/app/static/js/main.js
 */
document.addEventListener('DOMContentLoaded', () => {
    const chatForm = document.getElementById('chat-form');
    const messageInput = document.getElementById('message-input');
    const chatContainer = document.getElementById('chat-container');

    // 添加消息到聊天界面
    function addMessage(content, isUser = true) {
        const messageDiv = document.createElement('div');
        messageDiv.className = `message ${isUser ? 'user-message' : 'assistant-message'}`;
        messageDiv.textContent = content;
        chatContainer.appendChild(messageDiv);
        chatContainer.scrollTop = chatContainer.scrollHeight;
    }

    // 显示打字指示器
    function showTypingIndicator() {
        const indicator = document.createElement('div');
        indicator.className = 'message assistant-message typing-indicator';
        indicator.innerHTML = '<span></span><span></span><span></span>';
        chatContainer.appendChild(indicator);
        chatContainer.scrollTop = chatContainer.scrollHeight;
        return indicator;
    }

    // 处理表单提交
    chatForm.addEventListener('submit', async (e) => {
        e.preventDefault();
        const message = messageInput.value.trim();
        if (!message) return;

        // 添加用户消息
        addMessage(message, true);
        messageInput.value = '';

        // 显示打字指示器
        const indicator = showTypingIndicator();

        try {
            // 发送请求到后端
            const response = await fetch('/chat', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: `message=${encodeURIComponent(message)}`
            });

            const data = await response.json();

            // 移除打字指示器
            indicator.remove();

            if (data.error) {
                addMessage(`错误: ${data.error}`, false);
            } else {
                addMessage(data.answer, false);
            }
        } catch (error) {
            indicator.remove();
            addMessage('抱歉，发生了一个错误。请稍后重试。', false);
            console.error('Error:', error);
        }
    });
});